package ThreadDemo.ThreadDemo6;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:周次煜
 * Date: 2024-07-22
 * Time：21:37
 */


/**
 * 题目：用三个线程打印十个 ABC
 * 1.先用for 循环进行嵌套
 * 2. 每个线程前面等待，后面接着唤醒下一个线程
 * 3. 最终用主线程唤醒
 * 4. 注意锁对象一定要和调用对象相同，否则会抛出异常。
 *
 *
 */
public class Demo3 {
    private static Object locker1 = new Object();
    private static Object locker2 = new Object();
    private static Object locker3 = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new  Thread(()->{
            for (int i = 0; i < 10; i++) {
                synchronized (locker1) {
                    try {
                        locker1.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }


                System.out.print("A");

                synchronized(locker2) {
                    locker2.notify();
                }
            }
        });

        Thread t2 = new  Thread(()->{
            for (int i = 0; i < 10; i++) {
                synchronized (locker2) {
                    try {
                        locker2.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.print("B");
                synchronized(locker3) {
                    locker3.notify();
                }
            }
        });

        Thread t3 = new  Thread(()->{
            for (int i = 0; i < 10; i++) {
                synchronized (locker3) {
                    try {
                        locker3.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("C");
                synchronized(locker1) {
                    locker1.notify();
                }
            }
        });




        t1.start();
        t2.start();
        t3.start();

        Thread.sleep(100);
        synchronized(locker1) {
            locker1.notify();
        }

        t1.join();
        t2.join();
        t3.join();
    }
}
